<?php

namespace GordenSong\Utils;

use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\MySqlSchemaManager;
use GordenSong\Exceptions\TableNotExistException;
use Illuminate\Support\Facades\Schema;

class DatabaseUtil
{
	/**
	 * @param string $connectionName
	 * @param bool $withPrefix
	 * @return array
	 */
	public static function allTableNames(string $connectionName, bool $withPrefix = true): array
	{
		$tableNames = DatabaseUtil::schemaManager($connectionName)->listTableNames();
		if ($withPrefix) {
			return $tableNames;
		}
		$tablePrefix = self::getPrefix($connectionName);

		return array_map(function ($tableName) use ($tablePrefix) {
			return substr($tableName, strlen($tablePrefix));
		}, $tableNames);
	}

	public static function getPrefix(string $connection): string
	{
		return Schema::connection($connection)->getConnection()->getTablePrefix();
	}

	/**
	 * 如 mysql, mssql, sqlite
	 * @param string $connection
	 * @return string
	 */
	public static function platform(string $connection): string
	{
		return Schema::connection($connection)
			->getConnection()
			->getDoctrineSchemaManager()
			->getDatabasePlatform()
			->getName();
	}

	/**
	 * @param string $connection
	 * @param string $tableWithoutPrefix
	 * @return bool
	 */
	public static function tableExist(string $connection, string $tableWithoutPrefix): bool
	{
		return Schema::connection($connection)->hasTable($tableWithoutPrefix);
	}

	/**
	 * @param string $connectionName
	 * @param string $table
	 * @throws TableNotExistException
	 */
	public static function assertTableExist(string $connectionName, string $table): void
	{
		if (!self::tableExist($connectionName, $table)) {
			throw new TableNotExistException($table);
		}
	}

	/**
	 * @param string $connectionName
	 * @return AbstractSchemaManager|\GordenSong\MySQL\MySqlSchemaManager
	 */
	public static function schemaManager(string $connectionName)
	{
		$schemaManager = Schema::connection($connectionName)->getConnection()->getDoctrineSchemaManager();
		if ($schemaManager instanceof MySqlSchemaManager) {
			$schemaManager = \GordenSong\MySQL\MySqlSchemaManager::fromDBALMySqlSchemaManager($schemaManager);
		}
		return $schemaManager;
	}
}